<?php
function createsessions($username,$password)
{
    $_SESSION["gdusername"] = $username;
    $_SESSION["gdpassword"] = $password; // md5($password);
}

function clearsessionscookies()
{
    unset($_SESSION['gdusername']);
    unset($_SESSION['gdpassword']);
    
    session_unset();    
    session_destroy(); 

    setcookie ("gdusername", "",time()-60*60*24*100, "/");
    setcookie ("gdpassword", "",time()-60*60*24*100, "/");
}

function confirmUser($username,$password,$url)
{
    // $md5pass = md5($password); // Not needed any more as pointed by ted_chou12
    /* Validate from the database but as for now just demo username and password */

    $xml = simplexml_load_string(file_get_contents(
       $url
      ,false
      ,stream_context_create(
        array('http' => array(
           'method'  => 'POST'
          ,'header'  => 'Content-type: text/xml'
          ,'content' => <<< EOPOST
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <SOAP-ENV:Body>
    <tns:LoginCheck xmlns:tns="http://map.asascience.com/oilmapwebservice20">
      <tns:userName>$username</tns:userName>
      <tns:passWord>$password</tns:passWord>
      <tns:lang_id>0</tns:lang_id>
    </tns:LoginCheck>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
EOPOST
        ))
      )
    ));

    $userXml = simplexml_load_string(sprintf("%s",$xml->children('http://schemas.xmlsoap.org/soap/envelope/')->{'Body'}[0]->children()->{'LoginCheckResponse'}[0]->children()->{'LoginCheckResult'}));

    if (!$userXml) {
      setcookie("failedLogin",true);
      return false;
    }
    else {
      setcookie("failedLogin");
      return true;
    }
}

function checkLoggedin($loginUrl)
{
    if(isset($_SESSION['gdusername']) AND isset($_SESSION['gdpassword']))
        return true;
    elseif(isset($_COOKIE['gdusername']) && isset($_COOKIE['gdpassword']))
    {
        if(confirmUser($_COOKIE['gdusername'],$_COOKIE['gdpassword'],$loginUrl))
        {
            createsessions($_COOKIE['gdusername'],$_COOKIE['gdpassword']);
            return true;
        }
        else
        {
            if ($_COOKIE['failedLogin']) {
              clearsessionscookies();
              setcookie("failedLogin",true);
            }
            else {
              clearsessionscookies();
            }
            return false;
        }
    }
    else
        return false;
}
?> 
